from django import forms
from .models import Bicycle, ViolationRecord, CollegeUser, ViolationSecretKey
from django.contrib.auth.models import User


class BicycleForm(forms.ModelForm):
    """自行车表单"""
    
    class Meta:
        model = Bicycle
        fields = [
            'model', 'owner_name', 'owner_student_id', 
            'category', 'class_name', 'phone_number',
            'purchase_date', 'color', 'college', 'image', 'notes'
        ]
        widgets = {
            'model': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入自行车型号'
            }),
            'owner_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入所有人姓名'
            }),
            'owner_student_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入学号'
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'class_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入班级'
            }),
            'phone_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入联系电话'
            }),
            'purchase_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'color': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入颜色'
            }),
            'college': forms.Select(attrs={
                'class': 'form-select'
            }),
            'image': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            }),
            'notes': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入备注信息'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置必填字段
        self.fields['model'].required = True
        self.fields['owner_name'].required = True
        self.fields['category'].required = True


class ViolationForm(forms.ModelForm):
    """违章记录表单"""
    
    class Meta:
        model = ViolationRecord
        fields = [
            'violation_type', 'description', 'location',
            'reporter_name', 'reporter_phone', 'violation_images'
        ]
        widgets = {
            'violation_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请详细描述违章情况'
            }),
            'location': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入违章地点'
            }),
            'reporter_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入检查人姓名（可选）'
            }),
            'reporter_phone': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入检查人电话（可选）'
            }),
            'violation_images': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置必填字段
        self.fields['violation_type'].required = True
        self.fields['description'].required = True
        self.fields['location'].required = True


class CollegeUserForm(forms.ModelForm):
    """学院用户表单"""
    
    username = forms.CharField(
        max_length=150,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入用户名'
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入密码'
        })
    )
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入邮箱'
        })
    )
    
    class Meta:
        model = CollegeUser
        fields = ['college', 'is_admin']
        widgets = {
            'college': forms.Select(attrs={
                'class': 'form-select'
            }),
            'is_admin': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
        }
    
    def save(self, commit=True):
        college_user = super().save(commit=False)
        
        # 创建用户账号
        user = User.objects.create_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password'],
            email=self.cleaned_data['email']
        )
        
        college_user.user = user
        
        if commit:
            college_user.save()
        
        return college_user


class ViolationSecretKeyForm(forms.ModelForm):
    """违章提交秘钥设置表单"""
    
    class Meta:
        model = ViolationSecretKey
        fields = ['secret_key', 'is_active']
        widgets = {
            'secret_key': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入4位数字秘钥',
                'maxlength': '4',
                'pattern': '[0-9]{4}',
                'title': '请输入4位数字'
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            })
        }
    
    def clean_secret_key(self):
        secret_key = self.cleaned_data.get('secret_key')
        if not secret_key:
            raise forms.ValidationError('秘钥不能为空')
        
        if not secret_key.isdigit():
            raise forms.ValidationError('秘钥必须是数字')
        
        if len(secret_key) != 4:
            raise forms.ValidationError('秘钥必须是4位数字')
        
        return secret_key


class ViolationFormWithSecret(forms.ModelForm):
    """带秘钥验证的违章记录表单"""
    secret_key = forms.CharField(
        max_length=4,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入4位管理秘钥',
            'maxlength': '4',
            'pattern': '[0-9]{4}',
            'title': '请输入4位数字秘钥'
        }),
        help_text='请输入管理员设置的4位数字秘钥'
    )
    
    class Meta:
        model = ViolationRecord
        fields = [
            'violation_type', 'location', 'description',
            'reporter_name', 'reporter_phone', 'violation_images'
        ]
        widgets = {
            'violation_type': forms.Select(attrs={'class': 'form-select'}),
            'location': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入违章地点'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请详细描述违章情况'
            }),
            'reporter_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入举报人姓名（可选）'
            }),
            'reporter_phone': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入举报人电话（可选）'
            }),
            'violation_images': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            })
        }
    
    def clean_secret_key(self):
        secret_key = self.cleaned_data.get('secret_key')
        if not secret_key:
            raise forms.ValidationError('请输入管理秘钥')
        
        is_valid, message = ViolationSecretKey.validate_key(secret_key)
        if not is_valid:
            raise forms.ValidationError(message)
        
        return secret_key


class BicycleEditFormWithSecret(forms.ModelForm):
    """带秘钥验证的自行车编辑表单"""
    secret_key = forms.CharField(
        max_length=4,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入4位管理秘钥',
            'maxlength': '4',
            'pattern': '[0-9]{4}',
            'title': '请输入4位数字秘钥'
        }),
        help_text='请输入管理员设置的4位数字秘钥'
    )
    
    class Meta:
        model = Bicycle
        fields = [
            'model', 'owner_name', 'owner_student_id', 
            'category', 'class_name', 'phone_number',
            'purchase_date', 'color', 'college', 'image', 'notes'
        ]
        widgets = {
            'model': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入自行车型号'
            }),
            'owner_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入所有人姓名'
            }),
            'owner_student_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入学号'
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'class_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入班级'
            }),
            'phone_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入联系电话'
            }),
            'purchase_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }),
            'color': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入颜色'
            }),
            'college': forms.Select(attrs={
                'class': 'form-select'
            }),
            'image': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            }),
            'notes': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': '请输入备注信息'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置必填字段
        self.fields['model'].required = True
        self.fields['owner_name'].required = True
        self.fields['category'].required = True
    
    def clean_secret_key(self):
        secret_key = self.cleaned_data.get('secret_key')
        if not secret_key:
            raise forms.ValidationError('请输入管理秘钥')
        
        is_valid, message = ViolationSecretKey.validate_key(secret_key)
        if not is_valid:
            raise forms.ValidationError(message)
        
        return secret_key